<template>
  <div class="my-orders">
    <el-card class="orders-card">
      <template #header>
        <div class="card-header">
          <h3>我的订单</h3>
          <div class="header-actions">
            <el-select v-model="statusFilter" placeholder="订单状态" @change="loadOrders" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="待取车" value="0"></el-option>
              <el-option label="已取车" value="2"></el-option>
              <el-option label="已还车" value="3"></el-option>
              <el-option label="待支付" value="4"></el-option>
              <el-option label="订单完成" value="5"></el-option>
            </el-select>
          </div>
        </div>
      </template>

      <div v-loading="loading" class="orders-content">
        <div v-if="orders.length === 0" class="empty-state">
          <el-empty description="暂无订单数据">
            <el-button type="primary" @click="$router.push('/user/carBrowse')">去租车</el-button>
          </el-empty>
        </div>

        <div v-else class="orders-list">
          <el-card v-for="order in orders" :key="order.id" class="order-item" shadow="hover">
            <div class="order-header">
              <div class="order-info">
                <span class="order-id">订单号：{{ order.id }}</span>
                <span class="order-time">{{ formatDateTime(order.startTime) }}</span>
              </div>
              <div class="order-status">
                <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
              </div>
            </div>

            <el-divider></el-divider>

            <div class="order-content">
              <el-row :gutter="20">
                <el-col :span="4">
<!--                  <img :src="order.images || '/default-car.jpg'" alt="车辆图片" class="car-image">-->
                  <img :src="`/api/file/download.do?filename=${order.images}`"
                       :alt="车辆图片" class="car-image" />
                </el-col>
                <el-col :span="12">
                  <div class="car-details">
                    <h4>{{ order.brand }} {{ order.model }}</h4>
                    <p>车牌号：{{ order.licensePlate }}</p>
                    <p>租车时间：{{ formatDate(order.startTime) }} 至 {{ formatDate(order.endTime) }}</p>
                    <p>租车天数：{{ order.rentDays }} 天</p>
                  </div>
                </el-col>
                <el-col :span="4">
                  <div class="price-info">
                    <p class="daily-rent">¥{{ order.dailyRent }}/天</p>
                    <p class="total-amount">总计：¥{{ order.estimatedTotalAmount }}</p>
                  </div>
                </el-col>
                <el-col :span="4">
                  <div class="order-actions">
                    <el-button size="small" @click="viewDetail(order)">详情</el-button>
                    <el-button
                      v-if="canCancel(order.status)"
                      size="small"
                      type="danger"
                      @click="cancelOrder(order)"
                    >
                      取消
                    </el-button>
                    <el-button
                      v-if="canPay(order.status)"
                      size="small"
                      type="primary"
                      @click="payOrder(order)"
                    >
                      支付
                    </el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="600px">
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.id }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(selectedOrder.status)">{{ getStatusText(selectedOrder.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="车辆信息">{{ selectedOrder.brand }} {{ selectedOrder.model }}</el-descriptions-item>
          <el-descriptions-item label="车牌号">{{ selectedOrder.licensePlate }}</el-descriptions-item>
          <el-descriptions-item label="取车时间">{{ formatDateTime(selectedOrder.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="还车时间">{{ formatDateTime(selectedOrder.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="租车天数">{{ selectedOrder.rentDays }} 天</el-descriptions-item>
          <el-descriptions-item label="日租金">¥{{ selectedOrder.dailyRent }}</el-descriptions-item>
          <el-descriptions-item label="预估总费用">¥{{ selectedOrder.estimatedTotalAmount }}</el-descriptions-item>
          <el-descriptions-item label="实际费用" v-if="selectedOrder.finalAmount">¥{{ selectedOrder.finalAmount }}</el-descriptions-item>
          <el-descriptions-item label="商家名称">{{selectedOrder.merchantName}}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{selectedOrder.merchantContact}}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{selectedOrder.merchantPhone}}</el-descriptions-item>
          <el-descriptions-item label="商家地址">{{selectedOrder.merchantAddress}}</el-descriptions-item>
          </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 取消订单对话框 -->
    <el-dialog v-model="cancelDialogVisible" title="取消订单" width="400px">
      <div class="cancel-form">
        <p>确定要取消这个订单吗？</p>
        <el-form>
          <el-form-item label="取消原因">
            <el-input
              v-model="cancelReason"
              type="textarea"
              :rows="3"
              placeholder="请输入取消原因（可选）"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmCancel" :loading="cancelling">确认取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserRentals, cancelRental } from '@/api/rental'
import { useUserInfoStore } from '@/stores/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 数据
const loading = ref(false)
const orders = ref([])
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const detailDialogVisible = ref(false)
const cancelDialogVisible = ref(false)
const selectedOrder = ref(null)
const cancelReason = ref('')
const cancelling = ref(false)

// 方法
const loadOrders = async () => {
  loading.value = true

  try {
    // 调用真实API
    const response = await getUserRentals({
      userId: userInfoStore.userInfo?.id || '', // 从用户状态获取当前登录用户ID
      status: statusFilter.value || '',
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })

    // 由于request拦截器已经处理了成功响应，这里直接使用数据
    orders.value = response.data.records || []
    total.value = response.data.count || 0
    
  } catch (error) {
    ElMessage.error('加载订单失败')
    console.error('加载订单失败:', error)
  } finally {
    loading.value = false
  }
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.getFullYear() + '-' + 
         String(d.getMonth() + 1).padStart(2, '0') + '-' + 
         String(d.getDate()).padStart(2, '0')
}

const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return formatDate(date) + ' ' + 
         String(d.getHours()).padStart(2, '0') + ':' + 
         String(d.getMinutes()).padStart(2, '0')
}

const getStatusType = (status) => {
  // 数字状态映射：0-待取车，2-已取车，3-已还车，4-待支付，5-订单完成
  const statusMap = {
    0: 'primary',    // 待取车
    2: 'success',    // 已取车
    3: 'warning',    // 已还车
    4: 'warning',    // 待支付
    5: 'success'     // 订单完成
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  // 数字状态映射：0-待取车，2-已取车，3-已还车，4-待支付，5-订单完成
  const statusMap = {
    0: '待取车',
    2: '已取车',
    3: '已还车',
    4: '待支付',
    5: '订单完成'
  }
  return statusMap[status] || '未知状态'
}

const canCancel = (status) => {
  // 待取车(0)和待支付(4)状态可以取消
  return [0, 4].includes(status)
}

const canPay = (status) => {
  // 待支付(4)状态可以支付
  return status === 4
}

const viewDetail = (order) => {
  selectedOrder.value = order
  detailDialogVisible.value = true
}

const cancelOrder = (order) => {
  selectedOrder.value = order
  cancelReason.value = ''
  cancelDialogVisible.value = true
}

const confirmCancel = async () => {
  cancelling.value = true

  try {
    // 调用取消订单API
    const response = await cancelRental({
      rentalId: selectedOrder.value.id,
      userId: userInfoStore.userInfo?.id || '', // 从用户状态获取当前登录用户ID
      reason: cancelReason.value
    })

    // 由于request拦截器已经处理了成功响应，这里直接处理成功逻辑
    ElMessage.success('订单取消成功')
    cancelDialogVisible.value = false
    loadOrders() // 重新加载订单列表
    
  } catch (error) {
    ElMessage.error('取消订单失败')
    console.error('取消订单失败:', error)
  } finally {
    cancelling.value = false
  }
}

const payOrder = (order) => {
  // 跳转到支付页面
  router.push(`/user/rental/payment/${order.id}`)
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrders()
}

// 初始化
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.my-orders {
  padding: 20px;
}

.orders-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.orders-content {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
}

.orders-list {
  margin-bottom: 20px;
}

.order-item {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  gap: 20px;
}

.order-id {
  font-weight: bold;
  color: #303133;
}

.order-time {
  color: #909399;
}

.car-image {
  width: 100%;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
}

.car-details h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.car-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.price-info {
  text-align: right;
}

.daily-rent {
  color: #909399;
  font-size: 14px;
  margin: 0 0 5px 0;
}

.total-amount {
  color: #e6a23c;
  font-weight: bold;
  font-size: 16px;
  margin: 0;
}

.order-actions {
  text-align: right;
}

.order-actions .el-button {
  margin-bottom: 5px;
  width: auto;
  min-width: 60px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail {
  margin-bottom: 20px;
}

.cancel-form p {
  margin-bottom: 20px;
  color: #606266;
}
</style>
